package com.sam.im.heiqun.uis.activities;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.weixinAPPIDInfo;
import com.sam.im.heiqun.entities.weixinAPPIDbean;
import com.sam.im.heiqun.entities.weixinBean;
import com.sam.im.heiqun.entities.weixinQRData;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.view.text.PasswordEditText;

import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SetPayPasswordActivity extends BaseSwipeBackActivity {

    private static final String TAG = SetPayPasswordActivity.class.getSimpleName();
    @BindView(R.id.hint_content)
    TextView hintContent;

    @BindView(R.id.password_Input_View)
    PasswordEditText passwordEditText;

    @BindView(R.id.next_finish)
    Button nextFinish;

    private int step = 1;    // 1 第一次输入     2 第二次输入
    private String firstPayPsd;
    private PGService mPGservice;
    private String type;
    private String nativeAuth;

    @Override
    public int getContentViewId() {
        return R.layout.activity_set_pay_password;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.set_pay_psd);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
        passwordEditText.setSpacingWidth(0);
        type = getIntent().getStringExtra("type");
        nativeAuth = getIntent().getStringExtra("nativeAuth");
    }

    @OnClick({R.id.next_finish})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.next_finish:
                doNextOrFinish();
                break;
        }
    }

    private void doNextOrFinish() {

        String payPsd = passwordEditText.getText().toString().trim();
        if (payPsd.length() == 6) {
            if (step == 1) {
                hintContent.setText(R.string.please_again_input_six_pay_psd);
                nextFinish.setText(getString(R.string.finish));
                firstPayPsd = payPsd;
                passwordEditText.setText("");
                step = 2;
            } else {
                if (payPsd.equals(firstPayPsd)) {
                    setPayPwd(payPsd);
                }
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (step == 2) {
                step = 1;
                hintContent.setText(getString(R.string.please_input_six_pay_psd));
                passwordEditText.setText("");
                nextFinish.setText(getString(R.string.next));
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);

    }

    /**
     * 设置支付密码
     */
    private void setPayPwd(String payPwd) {
        showProgress(null);
        final String payPsd = MD5.MD532(payPwd);
        mPGservice.setPayPwd(payPsd, ToolsUtils.getMyUserId(),nativeAuth).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info","ex"+ex.getDisplayMessage()+ex.getCode());
                hideProgress();
                try {
                    String displayMessage = ex.getDisplayMessage();
                    JSONObject obj = new JSONObject(displayMessage);
                    JSONObject data = obj.getJSONObject("data");
                    String info = data.getString("info");
                    showToast(info+"");
                    finish();
                }catch (Exception e){
                    ToolsUtils.showToast(SetPayPasswordActivity.this,getResources().getString(R.string.caozuo_fail));
                }
            }
            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                hideProgress();
                showToast(getResources().getString(R.string.set_success));
                UserEntivity user = ToolsUtils.getUser();
                user.setPayInfo(payPsd);
                user.save();
                finish();
            }
        });
    }

    /**
     * 海外用户支付
     */
    private void doOverSeasPay(String moneyStr) {
        String uid = ToolsUtils.getMyUserId();

        String payUrl = "http://120.27.214.115:8088/Checkout/api.php?name=ACU&price=" + moneyStr + "&num=1&total=" + moneyStr + "&uid=" + uid;

        Intent intent = new Intent(SetPayPasswordActivity.this, RechargeWebViewActivity.class);
        intent.putExtra("payUrl", payUrl);
        hideProgress();
        startActivity(intent);
    }


    /**
     * 大陆支付，微信二维码支付，登录
     * {"data":{"username":"1385454002009","token":"E6Tv6goZrQcgVLGWDRrhN1TwWfLTO4sfmzwMaRD2zFOOUN7G"},"code":0,"msg":""}
     */
    private void login(final double moneyStr) {
        showProgress(null);
        mPGservice.login("1385454002009", "123456").subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.weixin_qr_pay_no));
                hideProgress();
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                getAppList(validateEntivity.getToken(), moneyStr);
            }
        });
    }

    /**
     * 获取用户APPID
     */
    private void getAppList(final String token, final double moneyStr) {
        mPGservice.getAppList(token).subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                String appid = "";
                if (ex.getCode() == 0) {
                    weixinAPPIDbean mweixinAPPIDbean = new Gson().fromJson(ex.getDisplayMessage(), weixinAPPIDbean.class);
                    List<weixinAPPIDInfo> mweixinAPPIDInfos = mweixinAPPIDbean.getMweixinAPPIDInfo();
                    if (null != mweixinAPPIDInfos && mweixinAPPIDInfos.size() > 0) {
                        appid = mweixinAPPIDInfos.get(0).getApp_id();
                    }
                    if (null != appid && !"".equals(appid)) {//再去请求
                        getPayCodeUrl(token, appid, moneyStr);
                    } else {
                        showToast(getResources().getString(R.string.weixin_qr_get_no));
                        hideProgress();
                    }
                } else {
                    showToast(getResources().getString(R.string.weixin_qr_get_no));
                    hideProgress();
                }
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_get_no));
            }
        });
    }

    /**
     * 获取自定义二维码
     */
    private void getPayCodeUrl(String token, String appid, final double moneyStr) {
        mPGservice.getPayCodeUrl(token, "" + (int) moneyStr, "ACU", appid).subscribe(new AbsAPICallback<weixinQRData>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_getqr_no));
            }

            @Override
            public void onNext(weixinQRData validateEntivity) {
                wxorders(ToolsUtils.getPhpUid(), validateEntivity.getOut_trade_no(), "" + (moneyStr / 100), validateEntivity.getNative_code_url());
            }
        });
    }

    /**
     * 获取自定义二维码
     */
    private void wxorders(String uid, final String outTradeNo, String money, final String url) {
//        Log.i(TAG, "wxorders: 0001");
        mPGservice.wxorders(uid, outTradeNo, money).subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_getor_no));
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                hideProgress();
/*{"data":{"info":{"ordersn":"2017012450971025"},"debugMsg":"","url":"api\/Api\/wxSaveOrder","msg":"","time":"1485247986"},"code":"1"}*/
                Bundle bundle = new Bundle();
                bundle.putString("self_code_url", url);
                startActivity(ShowQRcodeActivity.class, bundle);

            }
        });
    }


}
